<template>
	<view class="content">
		<view class="avautar">
			<button class="avatar-wrapper" style="width: 100%;height: 100%;padding: 0;background: transparent;border-radius: 50%;" open-type="chooseAvatar" @chooseavatar="onChooseAvatar">
				<image v-if="avatar" class="avatar" :src="avatar" mode="aspectFill"></image>
				<image v-if="!avatar" class="avatar" src="https://mp-fff067d4-0ad0-46f1-8940-3076faaf2173.cdn.bspapp.com/image/static/default.png" mode="aspectFill"></image>
			</button> 
		</view>
		<u--form
			labelPosition="left"
			:model="userInfo"
			ref="uForm"
		>
			<u-form-item
					label="昵称"
					prop="userInfo.nickname"
					borderBottom
			>
				<input type="nickname" class="weui-input" @blur="bindKeyInput" :value="userInfo.nickName" placeholder="请输入昵称"/>
			</u-form-item>
		</u--form>
		<view class="foot">
			<u-button shape="circle" type="primary" text="保 存" @click="saveFn"></u-button>
		</view>
	</view>
</template>

<script>
	import { navigateTo,getStorageSync,navigateBack } from '@/static/utils'
	export default {
		data() {
			return {
				userInfo: {},
				avatar:"",
			}
		},
		onShow() {
			if (!this.userInfo._id) {
				this.userInfo = getStorageSync('userInfo') || {}
				this.avatar = this.userInfo.avatar || ""
			}
		},
		methods: {
			bindKeyInput(e) {
				console.log(e);
				this.userInfo.nickName = e.detail.value
				console.log(this.userInfo);
			},
			saveFn(){
				const data = {
					_id:getStorageSync('userInfo')._id || "",
					avatar:this.avatar || "",
					nickName:this.userInfo.nickName|| ""
				}
				uni.request({
					url: 'https://fc-mp-fff067d4-0ad0-46f1-8940-3076faaf2173.next.bspapp.com/updateUser',
					data: data,
					success: (res) => {
						console.log(res);
						if (res.data.code == 200) {
							uni.showToast({
								icon: 'success',
								title: '保存成功！'
							});
							navigateBack(1)
						} else {
							uni.showToast({
								icon: 'none',
								title: "保存失败！"
							});
						}
					}
				})
			},
			onChooseAvatar(e) {
				const { avatarUrl } = e.detail 
				uni.showLoading({
						title: '上传中...',
				})
				let that = this
				uniCloud.uploadFile({
					filePath:avatarUrl,			//所上传文件的路径地址；
					cloudPath: Date.now() + '.jpg',  //保存在云端的文件名，这里以时间戳命名
					success(res){
						console.log(res);
						uni.hideLoading()
						that.avatar = res.fileID
						console.log(that.avatar);
					},
					fail(res){
						console.log(res)
					}
				})
			},
		}
	}
</script>

<style scoped lang="less">
	.content{
		width: 100%;
		height: 100%;
		padding: 0 20rpx;
		box-sizing: border-box;
	}
.avatar-wrapper {
  padding: 0;
  width: 80px !important;
  border-radius: 8px;
  margin-top: 40px;
  margin-bottom: 40px;
}

.avatar {
  display: block;
  width: 80px;
  height: 80px;
}

.container {
  display: flex;
}
.foot{
  width: 100%;
  position: fixed;
  bottom: 0;
  left: 0;
  padding: 20rpx;
  box-sizing: border-box;
	/deep/ .u-button--primary {
		width: 100% !important;
	}

}
</style>
